package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;


@Component
@Slf4j
public class WebSocketClientSingleton {
    private static CustomizedWebSocketClient client;
    private WebSocketClientSingleton(){}

    public static CustomizedWebSocketClient getInstance() throws URISyntaxException {
        if (client == null || client.isClosed()) {
            String webSocketUri = "ws://localhost:8081";
            try {
                //实例WebSocketClient对象，并连接到WebSocket服务端
                client = new CustomizedWebSocketClient(new URI(webSocketUri));
                client.connect();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (Exception e) {
//                client = new CustomizedWebSocketClient(new URI(webSocketUri));
//                client.connect();
//                throw new RuntimeException(e);
            }
//            return client;
        }
        return client;
    }

    public static void closeClient(CustomizedWebSocketClient client){
        client.close();
    }
}
